﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;

namespace TaoBaoProject.Handlers.OtherHanders
{
  /// <summary>
  /// Summary description for HandlerRequireProjects
  /// </summary>
  public class HandlerRequireProjects : IHttpHandler
  {

    public void ProcessRequest(HttpContext context)
    {
      context.Response.ContentType = "text/plain";
      string str = context.Request.QueryString["val"].ToString();
      if (str.Trim() == "")
      {
        context.Response.Write("没有设置任何必填字段，请重试！");
      }
      else
      {
        try
        {
          string filePath = context.Server.MapPath("~/Config/isRequiredItems.xml");
          str = str.Substring(0, str.Length - 1);
          string[] allItems = str.Split(';');

          XmlDocument xml = new XmlDocument();
          xml.Load(filePath);
          XmlNode root = xml.SelectSingleNode("Projects");
          XmlNodeList list = root.ChildNodes;
          SetAllProjectsFalse(list, xml, filePath);
          SetSomeProjectTrue(list, xml, filePath, allItems);
          context.Response.Write("Success");
        }
        catch (Exception ex)
        {
          context.Response.Write("设置失败");
        }
      }
    }
    private void SetAllProjectsFalse(XmlNodeList nodeList, XmlDocument xml, string path)
    {
      for (int i = 0; i < nodeList.Count; i++)
      {
        XmlElement ement = (XmlElement)nodeList[i];
        ement.SetAttribute("isRequired", "false");
      }
      xml.Save(path);
    }
    private void SetSomeProjectTrue(XmlNodeList nodeList, XmlDocument xml, string path, string[] allItems)
    {
      for (int i = 0; i < nodeList.Count; i++)
      {
        for (int j = 0; j < allItems.Length; j++)
        {
          if (nodeList[i].Name == allItems[j])
          {
            XmlElement xe = (XmlElement)nodeList[i];
            xe.SetAttribute("isRequired", "true");
          }
        }
      }
      xml.Save(path);
    }

    public bool IsReusable
    {
      get
      {
        return false;
      }
    }
  }
}